package com.qmyx.supply.admin.annotation.oplog;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * 操作日志
 * 使用说明：
 * 只需要在controller的方法中加上：OperationLogger.log("xxx"); 即可
 */
@Slf4j
@Configuration
public class OperationLogger {

    private final static ThreadLocal<List<String>> OPERACTION_LOGGER_CONTEXT = new ThreadLocal<List<String>>();

    private final static int REMARK_LENGTH = 4000;

    /**
     * 记录操作日志明细
     * @param message
     */
    public static void log(String message){
        List<String> data = OPERACTION_LOGGER_CONTEXT.get();
        if(data == null){
            data = new ArrayList<>();
            OPERACTION_LOGGER_CONTEXT.set(data);
        }
        data.add(message);
    }


    /**
     * 获取当前线程变量的日志内容
     * @return
     */
    protected static String getRemark(){
        List<String> data = OPERACTION_LOGGER_CONTEXT.get();
        if(data != null){
            StringBuffer buffer = new StringBuffer();
            data.forEach(s -> buffer.append(s).append("\n"));
            return StringUtils.left(buffer.toString(),REMARK_LENGTH);
        }
        return null;
    }


    /**
     * 移除本地变量
     */
    public static void clear() {
        OPERACTION_LOGGER_CONTEXT.remove();
    }

}
